package com.lzq.mq.nameserver.event.spi.listener;

import com.alibaba.fastjson2.JSON;
import com.lzq.mq.common.coder.TcpMsg;
import com.lzq.mq.common.enums.NameServerEventCode;
import com.lzq.mq.common.event.Listener;
import com.lzq.mq.nameserver.common.CommonCache;
import com.lzq.mq.nameserver.enums.ReplicationMsgTypeEnum;
import com.lzq.mq.nameserver.event.model.ReplicationMsgEvent;
import com.lzq.mq.nameserver.event.model.SlaveReplicationMsgAckEvent;
import com.lzq.mq.nameserver.store.ServiceInstance;
import lombok.extern.slf4j.Slf4j;

/**
 * 主从模式下, 从节点接收主节点的同步数据
 */
@Slf4j
public class ReplicationSlaveReciveMasterMsgListener implements Listener<ReplicationMsgEvent> {


    @Override
    public void onReceive(ReplicationMsgEvent event) throws Exception {
        ServiceInstance serviceInstance = event.getServiceInstance();
        //从节点接收主节点同步数据逻辑
        SlaveReplicationMsgAckEvent slaveReplicationMsgAckEvent = new SlaveReplicationMsgAckEvent();
        slaveReplicationMsgAckEvent.setMsgId(event.getMsgId());
        /*
        register和heartbeat都可以通过直接put实例实现,有点草率啊
         */
        if (event.getType().equals(ReplicationMsgTypeEnum.REGISTRY.getCode())) {
            CommonCache.getServiceInstanceManager().put(serviceInstance);
        } else {
            CommonCache.getServiceInstanceManager().putIfExist(serviceInstance);
        }

        log.info("从节点同步数据:{}", serviceInstance);
        // 返回ack
        byte[] jsonBytes = JSON.toJSONBytes(slaveReplicationMsgAckEvent);
        TcpMsg tcpMsg = new TcpMsg(
                NameServerEventCode.SLAVE_REPLICATION_ACK_MSG.getCode(),
                jsonBytes
        );
        event.getChannelHandlerContext().channel().writeAndFlush(tcpMsg);
    }
}